﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Microsoft.Practices.Unity;

namespace MyAMS.WebServer.ActionFilter
{
    class ActionFilterRegistry : IActionFilterRegistry
    {
        private readonly IUnityContainer container;
        private readonly List<ActionFilterRecord> registry;

        public ActionFilterRegistry(IUnityContainer container)
        {
            this.container = container;
            registry = new List<ActionFilterRecord>();
        }

        #region IActionFilterRegistry Members

        public void Clear()
        {
            registry.Clear();
        }

        public void Register(IEnumerable<IActionFilterCriteria> criteria, Type filterType)
        {
            registry.Add(new ActionFilterRecord(criteria, filterType));
        }

        public FilterInfo GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            FilterInfo filters = new FilterInfo();

            foreach (ActionFilterRecord record in registry)
            {
                if (record.Match(controllerContext, actionDescriptor))
                {
                    object filterObject = container.Resolve(record.FilterType);

                    if (filterObject is IActionFilter)
                    {
                        filters.ActionFilters.Add((IActionFilter)filterObject);
                    }

                    if (filterObject is IAuthorizationFilter)
                    {
                        filters.AuthorizationFilters.Add((IAuthorizationFilter)filterObject);
                    }

                    if (filterObject is IExceptionFilter)
                    {
                        filters.ExceptionFilters.Add((IExceptionFilter)filterObject);
                    }

                    if (filterObject is IResultFilter)
                    {
                        filters.ResultFilters.Add((IResultFilter)filterObject);
                    }
                }
            }

            return filters;
        }

        #endregion
    }
}
